<template>
    <div class="page add-member">
        <div class="weui-cells weui-cells_form">
            <div class="weui-cell phone-num">
                <div class="weui-cell__hd"><label class="weui-label">手机号</label></div>
                <div class="weui-cell__bd">
                    <input v-model="item.mobile" class="weui-input" type="tel" placeholder="必填" maxlength="11">
                </div>
                <span class="icon bg_sprite" @click="tellBook"></span>
            </div>
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">姓名</label></div>
                <div class="weui-cell__bd">
                    <input v-model="item.name" :value="item.name" class="weui-input" type="text" placeholder="必填" maxlength="10">
                </div>
            </div>
        </div>
        <div class="weui-cells">
            <!-- <a @click="selectGroup" class="weui-cell weui-cell_access">
                <div class="weui-cell__bd">
                    <p><span :value="item.groupId" class="title">所在小组</span>{{item.groupName}}</p>
                </div>
                <div class="weui-cell__ft">
                </div>
            </a> --> 
            <a @click="selectRole" class="weui-cell weui-cell_access">
                <div class="weui-cell__bd">
                    <p><span :value="item.roleId" class="title">项目角色</span>{{item.roleName}}</p>
                </div>
                <div class="weui-cell__ft">
                </div>
            </a>
        </div>
        <p style="text-align: center;margin-top: 10px;font-size: 13px;color: #ccc;">添加成功后会给项目成员发送邀请短信</p>
    </div> 
</template>

<script>
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import $ from 'zepto'
    import cache from 'gapi/cache'
    import clientInfo from 'gapi/clientInfo'
    import * as util from 'js/util.js'
    import clientUi from 'gapi/clientUi'
    import widget from 'gapi/widget'
    import commonPage from 'clientApi/commonPage.js'
    import teamApi from 'clientApi/teamApi.js'


    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */

    /**
     *  组件实例对象
     */
    export default {
        components: {

        },
        data: function(){
            return{
                item: {
                    roleName: '管理员',
                    roleId: 2,//管理员
                    groupName: '',
                    groupId: '',
                    mobile: '',
                    name: ''
                },
                tellname:''
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        watch: {
          'item.mobile': function(newVal, oldVal){
            if(/^\d{11}$/.test(newVal)){
              // 通过验证，自动匹配姓名
              util.ajax({
                  url:'/user/register/info',
                  type:'GET',
                  data:{
                      team_id: this.teamId,
                      project_id: this.projectId,
                      mobile: newVal
                  },
                  success:(result) => {
                      if(result.errno == 0){
                        this.item.name = result.data.real_name || ''
                        // this.item.name = result.data.real_name
                      }else{
                        widget.toast(result.errmsg)
                      }
                  },
                  error: (xhr, status) => {
                      // error
                      widget.toast('服务器异常')
                  },
                  noNetwork: () => {
                      // 无网络的回调
                      widget.toast('网络连接失败，请检查网络')
                  }
              })
            }else{
              this.item.name = ''
            }
          }
        }, 
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){

              this.projectId = util.getUrddataString('pId')
              this.teamId = util.getUrddataString('tId')
              this.userId = util.getUrddataString('uId')
              this.groupId = util.getUrddataString('gId')
              this.item.groupName = util.getUrddataString('gName')
              this.type = util.getUrddataString('type')
              this.item.groupId = this.groupId

              // this.$watch('item', (newe,old) => {
              //     if((/^1(3|4|5|7|8)\d{9}$/.test(newe.mobile))){ 
              //         console.log(newe.mobile)
              //         this.mobileIsRegister(newe.mobile)
              //     }
              // }, {deep: true})
            },
             /*判断手机号是否注册过----否，正常使用；是，返回姓名*/
            mobileIsRegister(mobile){
                util.ajax({
                    url:'/user/register/info',
                    type:'POST',
                    data:{
                        team_id: this.teamId,
                        project_id: this.projectId,
                        mobile: mobile
                    },
                    timeout:10000,
                    success:(obj) => {
                        console.log(JSON.stringify(obj))
                        if(obj&&obj.errno == 0){
                            if(obj.data.real_name){
                                this.item.name = obj.data.real_name
                            }
                        }else{
                            widget.toast(obj.errmsg)
                        }
                    },
                    error: (xhr, status) => {
                        widget.toast('服务器异常')
                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            tellBook (){
              teamApi.addFromContacts()
            },
             //更新小组&角色
            updateData (data){
                console.log(data)
                if(data.key&&data.key=='selectRole'){
                    this.item.roleId = data.value.id
                    this.item.roleName = data.value.name
                }
                // switch(data.key){
                //     case 'selectGroup':
                //         // this.item.groupId = data.value.id
                //         this.item.groupName = data.value.name
                //         break
                //     case 'selectRole':
                //         this.item.roleId = data.value.id
                //         this.item.roleName = data.value.name
                //         break
                // }
            },
            selectGroup(){
                cache.setMemoryCache('KqCacheMessge', {
                  project_id: this.projectId,
                  team_id: this.teamId,
                })
                location.href = "dmsaas://GroupSelectSingle?" + encodeURIComponent(`group_id=${this.item.groupId}`)
            },
            selectRole(){
              commonPage.getWebViewID((data)=>{
                cache.setMemoryCache('webViewID',{'webViewID':data})
              })
              location.href = "dmsaas://ProjectRole?urdData=" + encodeURIComponent(`tId=${this.teamId}&pId=${this.projectId}&uId=${this.userId}`)
            },
            doSubmit (){
                if(!this.item.mobile){
                    widget.toast('请输入手机号')
                    return
                }else if (this.item.mobile.length != 11){
                    widget.toast('请输入正确的手机号')
                    return
                }else if (!this.item.name){
                    widget.toast('请输入姓名')
                    return
                }else if (!this.item.groupId) {
                  widget.toast('请选择小组')
                  return
                }else if (!this.item.roleId) {
                  widget.toast('请选择身份')
                  return
                }else if(this.item.name.length > 10){
                  widget.toast('姓名不能超过10个字')
                  return
                }
                console.log(this.item.name)
                console.log(this.item.mobile)
                console.log(this.item.roleId)
                console.log(this.item.groupId)
                util.ajax({
                    url:'/group/member_add',
                    type:'POST',
                    data:{
                        user_list: JSON.stringify([
                          {
                             "user_name":this.item.name,
                             "phone": this.item.mobile,
                             "identity":this.item.roleId,
                             "group_id":this.item.groupId
                         }
                       ]),
                        team_id: this.teamId,
                        project_id: this.projectId,
                        source : 3 //1二维码 2微信邀请 3手动添加 4团队成员 5通讯录
                    },
                    timeout:10000,
                    beforeSend: () => {

                    },
                    success:(result) => {
                        // console.log('结果'+JSON.stringify(result))
                        if(result.errno == 0){
                            if (!result.data.length) {
                                widget.toast('该成员已在项目中,不能重复添加');
                                return;
                            }
                          widget.toast('添加人员成功')
                          commonPage.goBack(1)
                          // if(this.type){
                          //   if(this.type == 1){
                          //     cache.getMemoryCache('xmAddMemberWebViewId',function(data){
                          //         console.log(data)
                          //         if(data){
                          //           commonPage.goBack(1, {}, data.webViewID)
                          //         }
                          //     })
                          //   }else if(this.type == 2){
                          //     cache.getMemoryCache('childGroupWebView',function(data){
                          //         console.log(data)
                          //         if(data){
                          //           commonPage.goBack(1, {}, data.webViewID)
                          //         }
                          //     })
                          //   }else{
                          //     cache.getMemoryCache('projectAddWebViewId',function(data){
                          //         console.log(data)
                          //         if(data){
                          //           commonPage.goBack(1, {}, data.webViewID)
                          //         }
                          //     })
                          //   }
                          
                          // }else{
                          //    cache.getMemoryCache('xmAddMemberWebViewId',function(data){
                          //         console.log(data)
                          //         if(data){
                          //           commonPage.goBack(1, {}, data.webViewID)
                          //         }
                          //     })
                          // }
                          
                        }else{
                           widget.toast(result.errmsg)
                        }
                    },
                    error: (xhr, status) => {
                        // error
                        widget.toast('服务器异常');
                        console.log(xhr)
                    },
                    complete: () => {

                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            }
        },
        created(){
            this.init();
            window.loadData = this.updateData
            window.doSubmit = this.doSubmit

            window.passSelectedContactor = (data) => {
                this.item.name = data.name;
                let phone = '"'+data.phoneNumber+'"';
                let yztell = phone.replace(/[^0-9]+/g, '');
                if(!(/^\d{11}$/.test(yztell))){ 
                    widget.toast('手机号格式错误')
                    return false; 
                }else{
                    this.item.mobile = yztell
                }
                // this.mobileIsRegister(this.item.mobile)
            }

        },
        ready (){
          //控制header
          commonPage.updateTitleBar({
              leftDisplay: false,
              rightDisplay: true,
              rightText: '完成',
              rightAction: 'doSubmit'
          })
        }

    }


</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/common.css"></style>
<style src="../../static/css/team.css"></style>
